package com.changgou.oauth.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.oauth.service.AuthService;
import com.changgou.oauth.util.AuthToken;
import com.changgou.oauth.util.CookieUtil;
import com.changgou.oauth.util.GitHubConstant;
import com.changgou.oauth.util.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
@RequestMapping("/oauth")
public class LoginRedirectController {
    @Autowired
    private AuthService authService;


    @Value("${auth.clientId}")
    private String clientId;
    @Value("${auth.clientSecret}")
    private String clientSecret;
    @Value("${auth.cookieDomain}")
    private String cookieDomain;
    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    @GetMapping("/toLogin")
    public String toLogin(@RequestParam(value = "from",required = false,defaultValue = "") String from, Model model){
        model.addAttribute("from","/api/cart/joinCart?from="+from);
        return "login";
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private HttpServletResponse response;

    //github登录，回调地址
    @RequestMapping("/callback")
    public String callback(@RequestParam("code")String code, HttpServletRequest req) throws Exception{

        if(!StringUtils.isEmpty(code)){


            //拿到我们的code,去请求token

            AuthToken token = authService.getToken(code);

            //将jit存储到客户端cookie
            saveJIt2Cookie(token.getJti(),response);

           return "close";


        }

        // 否则返回到登陆页面
        return "http://localhost:8080/#/login";
    }

    private void saveJIt2Cookie(String jti,HttpServletResponse response) {
        CookieUtil.addCookie(response,cookieDomain,"/","uid",jti,cookieMaxAge,false);
    }

    @GetMapping("/githubLogin")
    public String githubLOgin(){
        return "redirect:"+GitHubConstant.CODE_URL;
    }
}
